import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Card, Form, Input, Space, Select, Button, Table } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'

// 引入请求函数
import {
  reqGetHospitalList,
  reqGetProvince,
  reqGetCityOrDistrict,
} from '@api/hospitalList'

// 引入ts类型
import {
  IhospitalList,
  IhospitalItem,
  IpcdList,
} from '@api/hospitalList/model/hospitalListTypes'

// 注意: Option组件是从Select组件中解构出来的
const { Option } = Select

// 用来标记用户是否点击查询按钮, true为点击 false为未点击
let flag = false
export default function HospitalList() {
  const navigate = useNavigate()
  const [form] = Form.useForm()
  // 存储表格数据的状态
  const [data, setData] = useState<IhospitalList>([])
  // 存储表格数据总数的状态
  const [total, setTotal] = useState(0)
  // 一页几条数据
  const [pageSize, setPageSize] = useState(2)
  // 页码高亮的状态
  const [page, setPage] = useState(1)

  // 正在加载的效果
  const [loading, setLoading] = useState(false)

  // 存储省数据
  const [province, setProvince] = useState<IpcdList>([])
  // 存储市数据
  const [city, setCity] = useState<IpcdList>([])
  // 存储区数据
  const [district, setDistrict] = useState<IpcdList>([])
  // 存储医院类型数据
  const [hosType, setHosType] = useState<IpcdList>([])

  // 省市区三个加载状态
  const [pload, setPload] = useState(false)
  const [cload, setCload] = useState(false)
  const [dload, setDload] = useState(false)
  useEffect(() => {
    // 组件挂载的时候获取表格数据
    getHospitalList(page, pageSize)
    // 获取省数据
    getProvince()
    // 获取医院类型
    getHosType()
  }, [])

  // 分页器的change事件
  function onChange(page: number, pageSize: number) {
    setPageSize(pageSize)
    setPage(page)

    getHospitalList(page, pageSize)
  }

  // 获取省数据函数
  async function getProvince() {
    setPload(true)
    const result = await reqGetProvince()
    setProvince(result)
    setPload(false)
  }
  // 获取市数据函数
  async function getCity(parentId: string) {
    setCload(true)
    const result = await reqGetCityOrDistrict(parentId)
    setCity(result)
    setCload(false)
  }
  // 获取区数据函数
  async function getDistrict(parentId: string) {
    setDload(true)
    const result = await reqGetCityOrDistrict(parentId)
    setDistrict(result)
    setDload(false)
  }

  // 获取医院类型数据函数
  async function getHosType() {
    const result = await reqGetCityOrDistrict('10000')
    setHosType(result)
  }

  // 获取医院列表表格数据的函数
  async function getHospitalList(page: number, pageSize: number) {
    setLoading(true)
    //  获取表单中筛选条件
    const params = form.getFieldsValue()
    //如果flag为true,则添加筛选,否则不添加筛选
    let result
    if (flag) {
      result = await reqGetHospitalList({
        page,
        limit: pageSize,
        ...params,
      })
    } else {
      result = await reqGetHospitalList({
        page,
        limit: pageSize,
      })
    }

    setData(result.content)
    setTotal(result.totalElements)
    setLoading(false)
  }

  // 查询按钮的事件处理函数
  function onFinish() {
    flag = true
    getHospitalList(1, pageSize)
    setPage(1)
  }
  const columns: ColumnsType<IhospitalItem> = [
    {
      title: '序号',
      render(a, b, index) {
        return index + 1
      },
      align: 'center', // 设置单元格内容居中对齐
      width: 80,
    },
    {
      title: '医院logo',
      render(_) {
        return (
          <img src={'data:image/png;base64,' + _.logoData} alt="" width="80" />
        )
      },
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      render(_) {
        return _.param.hostypeString
      },
    },
    {
      title: '详细地址',
      render(_) {
        return _.param.fullAddress
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        return status ? '已上线' : '未上线'
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '操作',
      render(_) {
        return (
          <Space>
            <Button
              type="primary"
              onClick={() => {
                navigate('/syt/hospital/hospitalList/show', {
                  state: _.id,
                })
              }}
            >
              查看
            </Button>
            <Button type="primary">排班</Button>
            <Button type="primary">上线</Button>
          </Space>
        )
      },
      width: 120,
    },
  ]
  return (
    <Card>
      <Form
        layout="inline"
        form={form}
        onFinish={onFinish}
        onValuesChange={() => {
          // 只要修改了表单中任何一个表单元素的值,就应该将flag设置为false
          flag = false
        }}
      >
        <Form.Item name="provinceCode" style={{ width: 200, marginBottom: 20 }}>
          <Select
            loading={pload}
            placeholder="请选择省"
            onChange={(value, data) => {
              // value是选中的Option的value值
              // data是选中的Option的value,key和children
              //清除选中的市和区数据
              form.setFieldsValue({ cityCode: '', districtCode: '' })
              // 一旦用户选择了指定的省,获取市数据
              getCity(value)
            }}
          >
            {province.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode" style={{ width: 200 }}>
          <Select
            loading={cload}
            placeholder="请选择市"
            onChange={(value) => {
              // 清空选中的区数据
              form.setFieldsValue({ districtCode: '' })
              // 当选择了市的时候,获取区数据
              getDistrict(value)
            }}
          >
            {city.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode" style={{ width: 200 }}>
          <Select placeholder="请选择区" loading={dload}>
            {district.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="hosname">
          <Input placeholder="医院名称"></Input>
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编码"></Input>
        </Form.Item>
        <Form.Item name="hostype" style={{ width: 200, marginBottom: 20 }}>
          <Select placeholder="医院类型">
            {hosType.map((item) => {
              return (
                <Option key={item.id} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="status" style={{ width: 200 }}>
          <Select placeholder="医院状态">
            {/* value="0" 这是字符串0 */}
            {/* value={0} 这是数字0 */}
            <Option value={0}>未上线</Option>
            <Option value={1}>已上线</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
            <Button
              onClick={() => {
                // 清空表单
                form.resetFields() //类似于form标签的reset方法
                flag = false
                // 重新获取数据
                getHospitalList(1, pageSize)
                setPage(1)
              }}
            >
              清空
            </Button>
          </Space>
        </Form.Item>
      </Form>
      <Table
        loading={loading}
        columns={columns}
        dataSource={data}
        rowKey={'id'}
        pagination={{
          current: page,
          total,
          pageSize,
          showSizeChanger: true,
          pageSizeOptions: [2, 5, 10],
          showQuickJumper: true,
          showTotal(total) {
            return `共${total}条`
          },
          onChange,
        }}
      ></Table>
    </Card>
  )
}
